'use client'
// PokerOvalReplayPlayer.tsx
// 統一整合版本，已取消元件拆分，確保可正常執行

import { useState, useEffect } from 'react'

interface Player {
  seat: number
  name: string
  chips: number
  cards: string[]
}

interface Action {
  type: string
  player?: number
  to?: number
  amount?: number
  cards?: string[]
  winner?: number
  label?: string
  hand?: string
}

const players: Player[] = [
  { seat: 1, name: 'You', chips: 926400, cards: ['A♥', '2♥'] },
  { seat: 2, name: 'Raffaele', chips: 1210000, cards: ['9♣', '9♦'] },
  { seat: 3, name: 'miuzic', chips: 852950, cards: ['K♥', 'J♣'] },
  { seat: 4, name: 'dit me may', chips: 2790000, cards: ['??', '??'] },
  { seat: 5, name: 'Anhlouis97', chips: 753800, cards: ['??', '??'] },
]

const actions: Action[] = [
  { type: 'bet', player: 1, amount: 10000, label: 'Raise' },
  { type: 'call', player: 2, amount: 10000, label: 'Call' },
  { type: 'call', player: 3, amount: 10000, label: 'Call' },
  { type: 'deal', cards: ['10♠', 'J♥', '2♦'] },
  { type: 'deal', cards: ['Q♠'] },
  { type: 'deal', cards: ['K♠'] },
  { type: 'pot' },
  { type: 'showdown' },
  { type: 'win', winner: 2, amount: 30000, hand: 'One Pair (9s)' },
]

export default function PokerOvalReplayPlayer() {
  const [step, setStep] = useState(0)
  const [isPlaying, setIsPlaying] = useState(false)
  const [bets, setBets] = useState<Record<number, number>>({})
  const [board, setBoard] = useState<string[]>([])
  const [showdown, setShowdown] = useState(false)
  const [winner, setWinner] = useState<number | null>(null)
  const [winnerAmount, setWinnerAmount] = useState<number | null>(null)
  const [winnerHand, setWinnerHand] = useState<string | null>(null)
  const [actionText, setActionText] = useState<Record<number, string>>({})
  const [showPotChip, setShowPotChip] = useState(false)

  const action = actions[step]

  useEffect(() => {
    if (!isPlaying || step >= actions.length - 1) return
    const timer = setTimeout(() => {
      nextStep()
    }, 1200)
    return () => clearTimeout(timer)
  }, [isPlaying, step])

  const nextStep = () => {
    const next = Math.min(step + 1, actions.length - 1)
    const a = actions[next]
    if ((a.type === 'bet' || a.type === 'call') && a.player !== undefined && a.amount) {
      setBets((prev) => ({ ...prev, [a.player!]: a.amount! }))
      setActionText((prev) => ({ ...prev, [a.player!]: a.label || a.type }))
      setTimeout(() => setActionText((prev) => ({ ...prev, [a.player!]: '' })), 1000)
    }
    if (a.type === 'deal' && a.cards) {
      setBoard((prev) => [...prev, ...a.cards])
    }
    if (a.type === 'pot') {
      setTimeout(() => setBets({}), 600)
    }
    if (a.type === 'showdown') {
      setShowdown(true)
    }
    if (a.type === 'win') {
      setWinner(a.winner || null)
      setWinnerAmount(a.amount || null)
      setWinnerHand(a.hand || null)
      setShowPotChip(true)
      setTimeout(() => {
        setShowPotChip(false)
        setWinner(null)
        setWinnerAmount(null)
        setWinnerHand(null)
      }, 1600)
    }
    setStep(next)
  }

  return (
    <div
      className="h-screen max-w-2xl w-full mx-auto bg-cover bg-center relative overflow-hidden"
      style={{ backgroundImage: 'url(/bg/poker-table-bg.png)' }}
    >
      <div className="absolute left-1/2 top-[28%] -translate-x-1/2 text-white text-xs z-10">
        POT 💰25,000
      </div>

      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-[35%] flex gap-1 z-10">
        {board.map((card, idx) => {
          const delay = idx * 0.2
          return (
            <div
              key={idx}
              className="w-8 h-12 bg-white text-black border rounded flex items-center justify-center text-xs font-bold animate-cardflip"
              style={{
                animationDelay: `${delay}s`,
                animationFillMode: 'backwards',
                transformOrigin: 'center center',
                position: 'relative',
                transform: 'scale(0.8)',
              }}
            >
              {card}
            </div>
          )
        })}
      </div>

      {showPotChip && winner !== null && (
        <div
          className="absolute z-30 text-yellow-300 font-bold text-xs animate-potfly"
          style={{ left: '50%', top: '28%' }}
        >
          💰
        </div>
      )}

      {players.map((player, i) => {
        const total = players.length
        const baseAngle = 270
        const angle = baseAngle + (360 / total) * i
        const radiusX = 42
        const radiusY = 48
        const rad = (angle * Math.PI) / 180
        const x = 50 + radiusX * Math.cos(rad)
        const y = 50 + radiusY * Math.sin(rad)

        const chipX = 50 + radiusX * Math.cos(rad) * 0.7
        const chipY = 50 + radiusY * Math.sin(rad) * 0.7

        const isHero = i === 0
        const isWinner = player.seat === winner
        const showCards =
          showdown || (bets[player.seat] !== undefined && step >= 1) ? player.cards : ['??', '??']
        const betAmount = bets[player.seat]

        return (
          <div key={player.seat}>
            <div
              className="absolute w-24 text-center text-xs transition-all duration-300"
              style={{ top: `${y}%`, left: `${x}%`, transform: 'translate(-50%, -50%)' }}
            >
              <div className={`font-semibold ${isHero ? 'text-yellow-300' : 'text-white'}`}>
                {player.name}
              </div>
              <div className="flex justify-center gap-1 mt-1">
                {showCards.map((c, j) => (
                  <div
                    key={j}
                    className={`w-8 h-12 border rounded flex items-center justify-center text-xs font-bold ${
                      isWinner ? 'bg-green-200 text-black' : 'bg-white text-black'
                    }`}
                  >
                    {c}
                  </div>
                ))}
              </div>
              <div className="text-yellow-500 mt-1">{player.chips.toLocaleString()} chips</div>
              {actionText[player.seat] && (
                <div className="mt-1 text-cyan-300 font-bold animate-fadein">
                  {actionText[player.seat]}
                </div>
              )}
              {isWinner && winnerAmount && (
                <div className="mt-1 text-green-300 font-bold animate-fadein">
                  +💰{winnerAmount.toLocaleString()}
                  {winnerHand && <div className="text-xs text-white">{winnerHand}</div>}
                </div>
              )}
            </div>

            {betAmount && (
              <div
                className="absolute text-red-300 text-sm font-semibold z-20 chip-fly"
                style={{ top: `${chipY}%`, left: `${chipX}%`, transform: 'translate(-50%, -50%)' }}
              >
                💰 {betAmount.toLocaleString()}
              </div>
            )}
          </div>
        )
      })}

      {step < actions.length - 1 && (
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-20">
          <button onClick={() => setStep((s) => Math.max(s - 1, 0))} className="text-white text-sm">
            Prev
          </button>
          <button onClick={() => setIsPlaying((p) => !p)} className="text-white text-sm">
            {isPlaying ? 'Pause' : 'Play'}
          </button>
          <button onClick={nextStep} className="text-white text-sm">
            Next
          </button>
        </div>
      )}

      <style jsx>{`
        @keyframes fadein {
          0% { opacity: 0; transform: scale(0.9); }
          100% { opacity: 1; transform: scale(1); }
        }
        .animate-fadein {
          animation: fadein 0.4s ease-in-out;
        }

        @keyframes cardflip {
          0% { transform: rotateY(90deg); opacity: 0; }
          100% { transform: rotateY(0deg); opacity: 1; }
        }
          50% { transform: rotateY(180deg); opacity: 0.5; }
          100% { transform: rotateY(0deg); opacity: 1; }
        }
        .animate-cardflip {
          animation: cardflip 0.5s ease-out;
        }

        @keyframes chiptrail {
          0% {
            opacity: 0;
            transform: scale(0.8) translateY(-10px);
          }
          50% {
            opacity: 1;
            transform: scale(1.1) translateY(0);
          }
          100% {
            opacity: 1;
            transform: scale(1) translateY(3px);
          }
        }
        .chip-fly {
          animation: chiptrail 0.6s ease-out;
        }

        @keyframes potfly {
          0% { opacity: 1; top: 28%; left: 50%; transform: translate(-50%, -50%) scale(1); }
          100% { opacity: 0; top: 75%; transform: translate(-50%, -50%) scale(0.8); }
        }
        .animate-potfly {
          animation: potfly 1.2s ease-in-out forwards;
        }
      `}</style>
    </div>
  )
}
